#!/bin/bash
# network_fix.sh - 网络修复脚本,需要sudo权限

echo "=== 开始网络修复 ==="

# 检查是否为root权限
if [ $EUID -ne 0 ]; then
    echo "请使用sudo运行此脚本"
    exit 1
fi

# 1. 停止相关服务
echo "停止网络服务..."
sudo systemctl stop NetworkManager
sudo systemctl stop systemd-resolved
sudo systemctl stop clash 2>/dev/null

# 2. 清理网络配置
echo "清理网络配置..."
sudo ip addr flush dev ens33
sudo dhclient -r
sleep 2

# 3. 重启网络服务
echo "重启网络服务..."
sudo systemctl start systemd-resolved
sudo systemctl start NetworkManager
sleep 3

# 4. 更新DNS配置（更可靠的方法）
echo "配置DNS..."
sudo rm -f /etc/resolv.conf
sudo ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf
echo "nameserver 114.114.114.114" | sudo tee -a /etc/resolv.conf

# 5. 重启网络接口
echo "重启网络接口..."
sudo netplan apply 2>/dev/null
sudo dhclient ens33

# 6. 等待网络就绪
echo "等待网络连接..."
for i in {1..10}; do
    if ping -c 1 -W 1 8.8.8.8 &>/dev/null; then
        echo "网络连接成功"
        break
    fi
    echo "等待网络... ($i/10)"
    sleep 2
done

# 7. 启动Clash
echo "启动Clash..."
sudo systemctl start clash 2>/dev/null
sleep 3

# 8. 检查Clash端口
echo "检查Clash端口..."
if netstat -tln | grep 7890 > /dev/null; then
    echo "Clash端口7890已就绪"
    
    # 设置代理环境变量
    export http_proxy=http://127.0.0.1:7890
    export https_proxy=http://127.0.0.1:7890
    export no_proxy=localhost,127.0.0.1
    
    echo "代理环境变量已设置"
else
    echo "警告: Clash端口7890未就绪"
fi

# 9. 测试网络
echo "=== 网络测试 ==="
ping -c 3 8.8.8.8
curl -I --connect-timeout 5 http://www.google.com >/dev/null 2>&1 && echo "外网访问: 成功" || echo "外网访问: 失败"

echo "=== 网络修复完成 ==="